const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const axios = require('axios');

const app = express();
const PORT = 5005;
const RULES_FILE = path.join(__dirname, '../data/ubbc-rules.json');
const TEMP_DIR = path.join(__dirname, '../temp');

app.use(cors());
app.use(express.json());

// 开放 temp 目录为静态资源
app.use('/temp', express.static(TEMP_DIR));

// 新增：图片下载接口
app.post('/api/download-image', async (req, res) => {
  const { image_url } = req.body;
  console.log('收到图片URL:', image_url);
  
  if (!image_url || typeof image_url !== 'string') {
    return res.status(400).json({ error: '缺少 image_url 参数' });
  }
  
  // 基本URL验证
  const urlRegex = /^https?:\/\/.+/i;
  if (!urlRegex.test(image_url.trim())) {
    return res.status(400).json({ error: 'URL格式无效，必须以http://或https://开头' });
  }
  
  try {
    // 检查 temp 目录
    if (!fs.existsSync(TEMP_DIR)) {
      fs.mkdirSync(TEMP_DIR, { recursive: true });
    }
    
    // 清理和验证URL
    let cleanUrl = image_url.trim();
    
    // 生成唯一文件名
    let ext = '.jpg'; // 默认扩展名
    try {
      const urlPath = new URL(cleanUrl).pathname;
      const pathExt = path.extname(urlPath.split('?')[0]);
      if (pathExt && /\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(pathExt)) {
        ext = pathExt.toLowerCase();
      }
    } catch (e) {
      console.log('无法解析URL路径，使用默认扩展名');
    }
    
    const filename = `img_${Date.now()}_${Math.floor(Math.random()*10000)}${ext}`;
    const filepath = path.join(TEMP_DIR, filename);
    
    console.log('处理后的URL:', cleanUrl);
    console.log('目标文件:', filepath);
    
    // 下载图片
    const response = await axios.get(cleanUrl, { 
      responseType: 'stream', 
      timeout: 15000,
      maxRedirects: 5,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'image/*,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Connection': 'keep-alive'
      }
    });
    
    // 检查响应内容类型
    const contentType = response.headers['content-type'];
    if (contentType && !contentType.startsWith('image/')) {
      return res.status(400).json({ error: `响应不是图片格式，实际类型: ${contentType}` });
    }
    
    const writer = fs.createWriteStream(filepath);
    response.data.pipe(writer);
    
    writer.on('finish', () => {
      console.log('图片保存成功:', filepath);
      res.json({ 
        success: true,
        local_url: `/temp/${filename}`,
        filename: filename,
        message: '图片下载成功'
      });
    });
    
    writer.on('error', err => {
      console.error('图片保存异常:', err);
      // 清理失败的文件
      if (fs.existsSync(filepath)) {
        fs.unlinkSync(filepath);
      }
      res.status(500).json({ error: '图片保存失败', detail: err.message });
    });
    
  } catch (err) {
    console.error('图片下载异常:', err);
    let errorMessage = '图片下载失败';
    
    if (err.code === 'ENOTFOUND') {
      errorMessage = '无法解析域名，请检查URL是否正确';
    } else if (err.code === 'ECONNRESET') {
      errorMessage = '连接被重置，请重试';
    } else if (err.code === 'ETIMEDOUT') {
      errorMessage = '请求超时，请检查网络连接或稍后重试';
    } else if (err.code === 'ECONNREFUSED') {
      errorMessage = '连接被拒绝，目标服务器可能不可用';
    } else if (err.response) {
      const status = err.response.status;
      if (status === 404) {
        errorMessage = '图片不存在(404)';
      } else if (status === 403) {
        errorMessage = '访问被拒绝(403)，可能需要权限';
      } else if (status === 500) {
        errorMessage = '服务器内部错误(500)';
      } else {
        errorMessage = `HTTP错误: ${status}`;
      }
    } else if (err.request) {
      errorMessage = '网络请求失败，请检查网络连接';
    } else if (err.message) {
      errorMessage = err.message;
    }
    
    res.status(500).json({ error: errorMessage, detail: err.message });
  }
});

// 读取规则文件
const readRules = () => {
  try {
    const data = fs.readFileSync(RULES_FILE, 'utf8');
    const json = JSON.parse(data);
    // 新格式：{ rules: [...] }
    return Array.isArray(json.rules) ? json.rules : [];
  } catch (error) {
    console.error('读取规则文件失败:', error);
    return [];
  }
};

// 写入规则文件
const writeRules = (rulesArr) => {
  try {
    fs.writeFileSync(RULES_FILE, JSON.stringify({ rules: rulesArr }, null, 4), 'utf8');
    return true;
  } catch (error) {
    console.error('写入规则文件失败:', error);
    return false;
  }
};

// 获取所有规则
app.get('/api/rules', (req, res) => {
  const rules = readRules();
  res.json(rules);
});

// 获取单个规则（通过下标）
app.get('/api/rules/:index', (req, res) => {
  const rules = readRules();
  const idx = parseInt(req.params.index, 10);
  if (isNaN(idx) || idx < 0 || idx >= rules.length) {
    return res.status(404).json({ error: '规则不存在' });
  }
  res.json(rules[idx]);
});

// 创建新规则
app.post('/api/rules', (req, res) => {
  const rules = readRules();
  const rule = req.body;
  // 可选：校验字段
  rules.push(rule);
  if (writeRules(rules)) {
    res.json({ success: true, message: '规则创建成功', index: rules.length - 1 });
  } else {
    res.status(500).json({ error: '保存失败' });
  }
});

// 更新规则（通过下标）
app.put('/api/rules/:index', (req, res) => {
  const rules = readRules();
  const idx = parseInt(req.params.index, 10);
  if (isNaN(idx) || idx < 0 || idx >= rules.length) {
    return res.status(404).json({ error: '规则不存在' });
  }
  rules[idx] = req.body;
  if (writeRules(rules)) {
    res.json({ success: true, message: '规则更新成功' });
  } else {
    res.status(500).json({ error: '保存失败' });
  }
});

// 删除规则（通过下标）
app.delete('/api/rules/:index', (req, res) => {
  const rules = readRules();
  const idx = parseInt(req.params.index, 10);
  if (isNaN(idx) || idx < 0 || idx >= rules.length) {
    return res.status(404).json({ error: '规则不存在' });
  }
  rules.splice(idx, 1);
  if (writeRules(rules)) {
    res.json({ success: true, message: '规则删除成功' });
  } else {
    res.status(500).json({ error: '保存失败' });
  }
});

// 搜索规则
app.get('/api/search', (req, res) => {
  const rules = readRules();
  const query = req.query.q;
  if (!query) {
    return res.json(rules);
  }
  const filtered = rules.filter(rule => {
    const matchesName = (rule['rules-name'] || '').toLowerCase().includes(query.toLowerCase());
    const matchesContent = Array.isArray(rule.conditions) && rule.conditions.some(condition =>
      (condition.content || '').toLowerCase().includes(query.toLowerCase())
    );
    return matchesName || matchesContent;
  });
  res.json(filtered);
});

app.listen(PORT, () => {
  console.log(`🚀 UBBC规则管理后端服务已启动`);
  console.log(`📡 服务地址: http://localhost:${PORT}`);
  console.log(`📁 规则文件: ${RULES_FILE}`);
});
